using UniversalAdminSystem.Application.Authentication.DTOs;
using UniversalAdminSystem.Application.Authentication.Interfaces;
using UniversalAdminSystem.Domian.UserManagement.IRepository;
using UniversalAdminSystem.Application.UserManagement.Interface;
using UniversalAdminSystem.Domian.UserManagement.ValueObj;

namespace UniversalAdminSystem.Application.Authentication.Service;

public class LoginAppService : ILoginAppService
{
    private readonly IUserRepository _userRepository;
    private readonly IJwtTokenService _jwtService;
    private readonly IPasswordHelper _passwordHelper;
    private readonly IUserInfoRepository _userInfoRepository;

    public LoginAppService(
        IUserRepository userRepository,
        IJwtTokenService jwtService,
        IPasswordHelper passwordHelper,
        IUserInfoRepository userInfoRepository)
    {
        _userRepository = userRepository;
        _jwtService = jwtService;
        _passwordHelper = passwordHelper;
        _userInfoRepository = userInfoRepository;
    }

    public async Task<LoginResultDto> LoginAsync(LoginDto dto)
    {
        
        var user = await _userRepository.GetUserByAccountAsync(dto.Account) ?? throw new Exception("账号不存在");
        var userinfo = await _userInfoRepository.GetByGuidAsync(user.UserInfoId ?? throw new Exception("用户信息未绑定")) ?? throw new Exception("用户信息不存在");
        // 使用密码验证服务进行安全比对
        if (!_passwordHelper.VerifyPasswordWithSeparateSalt(dto.Password, user.Password, user.Salt)) throw new Exception("密码错误");
        // 生成JWT令牌
        var token = _jwtService.GenerateToken(user.UserId.Value.ToString(), user.RoleId?.Value.ToString() ?? "", user.Status);
        // 返回登录结果
        return new LoginResultDto(token, user.UserId.Value.ToString(), user.RoleId?.Value.ToString() ?? "", user.Account.Value.ToString(),userinfo);
    }
}